package com.qiezi.project.activity;


import android.Manifest;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hjq.dialog.WaitDialog;
import com.qiezi.App;
import com.qiezi.R;
import com.qiezi.base.BaseMvpActivity;
import com.qiezi.bean.AgentBean;
import com.qiezi.bean.PaypalBean;
import com.qiezi.mvp.CreatePresenter;
import com.qiezi.project.adapter.CategoryAdapter;
import com.qiezi.project.contract.InvitationContract;
import com.qiezi.project.dialog.CreateUserDialog;
import com.qiezi.project.dialog.GetMoneyDialog;
import com.qiezi.project.dialog.ManageDialog;
import com.qiezi.project.view.BlockView;
import com.qiezi.util.Util;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

@CreatePresenter(presenter = InvitationContract.Presenter.class)
public class InvitationActivity extends BaseMvpActivity<InvitationContract.Presenter> implements InvitationContract.View, View.OnClickListener,EasyPermissions.PermissionCallbacks {


    @BindView(R.id.tv_back)
    TextView tvBack;

    @BindView(R.id.iv_posters)
    SimpleDraweeView ivQR;

    @BindView(R.id.tv_open)
    TextView tvOpen;

    @BindView(R.id.bv_register_num)
    BlockView bvRegNum;

    @BindView(R.id.bv_total_income)
    BlockView bvTotalIncome;

    @BindView(R.id.bv_team_num)
    BlockView bvTeamNum;

    @BindView(R.id.bv_register_num_today)
    BlockView bvRegNumToday;

    @BindView(R.id.bv_total_income_today)
    BlockView bvTotalIncomeToday;

    @BindView(R.id.bv_team_num_today)
    BlockView bvTeamNumToday;

    @BindView(R.id.rl_recommend)
    View Rlrecommend;

    @BindView(R.id.tv_manage)
    TextView tvManage;

    @BindView(R.id.tv_getMoney)
    TextView tvGetMoney;

    @BindView(R.id.tv_money)
    TextView tvMoney;

    @BindView(R.id.tv_copy)
    TextView tvCopy;

    @BindView(R.id.tv_save)
    TextView tvSave;

    @BindView(R.id.layout_root)
    View rootView;


    private String url,name,addr,money;

    @Override
    protected void onSaveInstanceState(Bundle paramBundle) {
        super.onSaveInstanceState(paramBundle);
        paramBundle.putString("url",url);
        paramBundle.putString("name",name);
        paramBundle.putString("addr",addr);
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_invitation;
    }

    private void setTypeface(){
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "fonts/iconfont.ttf");
        tvBack.setTypeface(iconfont);
    }

    @Override
    protected void initData(Bundle saveBundle) {
        setTypeface();
        if (saveBundle != null){
            url = saveBundle.getString("url");
            name = saveBundle.getString("name");
            addr = saveBundle.getString("addr");
        }else {
            rootView.setVisibility(View.GONE);
            getPresenter().loadData();
        }

    }



    @Override
    protected void initListener() {
        tvBack.setOnClickListener(this);
        tvOpen.setOnClickListener(this);
        tvGetMoney.setOnClickListener(this);
        tvManage.setOnClickListener(this);
        tvCopy.setOnClickListener(this);
        tvSave.setOnClickListener(this);
    }

    WaitDialog.Builder waitDialog;



    private boolean createUser(String user,String pwd,String address){
        if (user == null || user.length() < 8){
            toast("账号长度应不小于8位数");
            return false;
        }

        if (pwd == null || pwd.length() < 8){
            toast("密码长度应不小于8个字符");
            return false;
        }

        if (address == null || address.length() <10){
            toast("地址长度应不小于10个字符");
            return false;
        }

        if (waitDialog != null){
            waitDialog.dismiss();
        }
        waitDialog =  new WaitDialog.Builder(this).setMessage("创建中...");
        waitDialog.show();
        getPresenter().createUser(user,pwd,address);

        return true;
    }


    private boolean login(String user,String pwd){
        if (user == null || user.length() < 8){
            toast("账号长度应不小于8位数");
            return false;
        }

        if (pwd == null || pwd.length() < 8){
            toast("密码长度应不小于8个字符");
            return false;
        }


        if (waitDialog != null){
            waitDialog.dismiss();
        }
        waitDialog =  new WaitDialog.Builder(this).setMessage("登录中...");
        waitDialog.show();
        getPresenter().login(user,pwd);

        return true;
    }


    private boolean logout(){
        if (waitDialog != null){
            waitDialog.dismiss();
        }
        waitDialog =  new WaitDialog.Builder(this).setMessage("退出登录中...");
        waitDialog.show();
        getPresenter().logout();

        return true;
    }

    private boolean getMoney(String money){
        if (money.length() == 0)return false;

        float price = 0;
        float maxMoney = 0;
        NumberFormat format = NumberFormat.getInstance();
        try{
            maxMoney = format.parse(this.money).floatValue();
            price = format.parse(money).floatValue();
        }catch (Exception e){
            e.printStackTrace();
            price = -1;
        }
        if (maxMoney == 0){
            showError("当前无可提现金额");
            return false;
        }else if (price <= 0){
            showError("请输入正确的金额格式");
            return false;
        }else if (price > maxMoney){
            showError("输入金额大于可提现金额");
            return false;
        }
        waitDialog =  new WaitDialog.Builder(this).setMessage("提现中...");
        waitDialog.show();
        getPresenter().paypal(money);
        return true;
    }


    @Override
    public void showError(String msg) {
        super.showError(msg);
        complete();
    }

    @Override
    public void complete() {
        super.complete();
        if (waitDialog != null) waitDialog.dismiss();
        waitDialog = null;
    }

    @Override
    public void onCreateUser() {
        getPresenter().loadData();
        complete();
        toast("创建成功");
    }


    private ManageDialog.Builder manageDialog;


    @Override
    protected void onStop() {
        log("stop");
        getPresenter().canceledCell();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        log("onDestroy");
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_open:

                if (url == null)return;
                new CreateUserDialog.Builder(this).setListener(new CreateUserDialog.OnListener() {
                    @Override
                    public void create(Dialog dialog, String user, String pwd, String address) {
                        if (createUser(user,pwd,address)){
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void login(Dialog dialog, String user, String pwd) {
                        if (InvitationActivity.this.login(user,pwd)){
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void cancel(Dialog dialog) {
                        InvitationActivity.this.getPresenter().canceledCell();
                    }
                }).show();
                break;
            case R.id.tv_manage:
                getPresenter().getPaypal();
                if (manageDialog != null) manageDialog.dismiss();
                manageDialog = new ManageDialog.Builder(this)
                        .setAddr(addr)
                        .setUsername(name)
                        .setListener(new ManageDialog.OnListener() {
                    @Override
                    public void modify(Dialog dialog, String address) {
                        if (modAddr(address)){
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void logout(Dialog dialog) {
                        if (InvitationActivity.this.logout()){
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void cancel(Dialog dialog) {
                        InvitationActivity.this.getPresenter().canceledCell();
                    }
                });
                manageDialog.show();
                break;
            case R.id.tv_getMoney:
                if (money == null)return;
                new GetMoneyDialog.Builder(this)
                        .setHintMoney(money)
                        .setListener(new GetMoneyDialog.OnListener() {

                    @Override
                    public void all(Dialog dialog, GetMoneyDialog.Builder builder) {
                        builder.setMoney(money);
                    }

                    @Override
                    public void confirm(Dialog dialog, String money) {
                        if (getMoney(money)){
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void cancel(Dialog dialog) {
                        InvitationActivity.this.getPresenter().canceledCell();
                    }
                }).show();

                break;
            case R.id.tv_copy:
                if (url == null)return;
                copy();
                break;
            case R.id.tv_save:
                if (url == null)return;
                requestPermission();
                break;
        }
    }

    @Override
    public void onModAddr() {
        getPresenter().loadData();
        toast("修改成功");
    }

    private boolean modAddr(String addr){
        if (addr == null || addr.length()<10){
            toast("请填写正确的提现地址");
            return false;
        }
        if (waitDialog != null){
            waitDialog.dismiss();
        }
        waitDialog =  new WaitDialog.Builder(this).setMessage("修改中...");
        waitDialog.show();
        getPresenter().modAddr(addr);
        return true;
    }

    @Override
    public void onPaypalList(ArrayList<PaypalBean> data) {

        if (manageDialog == null)return;
        if (data == null || data.size() == 0){
            manageDialog.setEmptyText("没有提现记录哦~！");
        }
        manageDialog.setData(data);
        manageDialog = null;
    }

    @Override
    public void onPaypalError() {
        if (manageDialog == null)return;
        manageDialog.setEmptyText("加载失败，请稍后重试");
        manageDialog = null;
    }

    private void saveImage(){
        ivQR.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(ivQR.getDrawingCache());
        ivQR.setDrawingCacheEnabled(false);
        boolean isSaveSuccess = Util.saveImageToGallery(this, bitmap);
        if (isSaveSuccess) {
            toast("保存图片成功");
        } else {
            toast("保存图片失败，请稍后重试");
        }
    }



    private static final int REQUEST_CODE_SAVE_IMG = 10;


    /**
     * 请求读取sd卡的权限
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //读取sd卡的权限
            String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(this, mPermissionList)) {
                //已经同意过
                saveImage();
            } else {
                //未同意过,或者说是拒绝了，再次申请权限
                EasyPermissions.requestPermissions(
                        this,  //上下文
                        "保存图片需要读取sd卡的权限", //提示文言
                        REQUEST_CODE_SAVE_IMG, //请求码
                        mPermissionList //权限列表
                );
            }
        } else {
            saveImage();
        }
    }

    private void copy(){
        if (url == null){
            toast("数据未加载好");
            return;
        }
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        ClipData clipData = ClipData.newPlainText(null, url);

        clipboard.setPrimaryClip(clipData);
        toast("已复制到粘贴板");
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private void isOpen(boolean open){
        if (open){
            tvOpen.setVisibility(View.INVISIBLE);
            Rlrecommend.setVisibility(View.VISIBLE);
        }else {
            tvOpen.setVisibility(View.VISIBLE);
            Rlrecommend.setVisibility(View.INVISIBLE);
        }
    }


    public void setAddr(String addr) {
        this.addr = addr;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMoney(String money) {
        this.money = money;
    }

    @Override
    public void onResultData(AgentBean data) {
        setUrl(data.getUrl());
        setAddr(data.getAddr());
        setName(data.getUsername());
        setMoney(data.getMoney());
//        setMoney("100.00");
        bvRegNum.setValue(data.getRegister_num());
        bvTotalIncome.setValue(data.getTotal_income());
        bvTeamNum.setValue(data.getTeam_num());
        bvRegNumToday.setValue(data.getRegister_num_today());
        bvTotalIncomeToday.setValue(data.getTotal_income_today());
        bvTeamNumToday.setValue(data.getTeam_num_today());
        tvMoney.setText(data.getMoney());
        Uri uri = Uri.parse(data.getQr());
        ivQR.setImageURI(uri);
        isOpen(data.isOpen());
        rootView.setVisibility(View.VISIBLE);
        complete();
    }

    @Override
    public void onPaypal() {
        getPresenter().loadData();
        toast("提现成功");
//        complete();
    }

    @Override
    public void onLogin(String token) {
        log("token:"+token);
        App.getInstance().setToken(token);
        App.getInstance().saveLocalData();//保存数据到本地
//        App.getInstance().setLogin(true);
        getPresenter().loadData();
        toast("登录成功");
    }

    @Override
    public void onLogout() {
        log("退出？？？");
        App.getInstance().setToken("null");
        App.getInstance().saveLocalData();//保存数据到本地
//        App.getInstance().setLogin(false);
        isOpen(false);
        complete();
        toast("退出成功");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        saveImage();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //打开系统设置，手动授权
            new AppSettingsDialog
                    .Builder(this)
                    .setRationale("没有该权限，此应用程序可能无法正常工作。打开应用设置屏幕以修改应用权限")
                    .setTitle("必需权限")
                    .build()
                    .show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            //拒绝授权后，从系统设置了授权后，返回APP进行相应的操作
            Log.i("", "onPermissionsDenied:------>自定义设置授权后返回APP");
            saveImage();
        }
    }
}
